﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Index;
using Lucene.Net.Analysis;
using System.IO;
using Lucene.Net.Documents;
using Lucene.Net.Search;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.QueryParsers;
using System.Diagnostics;
using Lucene.Net.Util;
using LuceneIO = Lucene.Net.Store;

namespace Lucene
{
    class Person
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string Info { get; set; }
        public Person()
            : this("1", "zzl", "test is a good!")
        { }
        public Person(string id, string name, string info)
        {
            this.ID = id;
            this.Name = name;
            this.Info = info;
        }
    }
    class Program
    {

        public static void SetOutput(string msg)
        {
            Console.WriteLine(msg);
        }


        Analyzer analyzer = null;
        DirectoryInfo dirInfo = null;
        LuceneIO.Directory directory = null;
        IndexSearcher searcher = null;
        public Program()
        {

            analyzer = new StandardAnalyzer();
            dirInfo = Directory.CreateDirectory(Config.INDEX_STORE_PATH);
            directory = LuceneIO.FSDirectory.Open(dirInfo);
            searcher = new IndexSearcher(Config.INDEX_STORE_PATH);

        }
        /// <summary>
        /// 显示搜索结果
        /// </summary>
        /// <param name="queryResult"></param>
        void ShowFileSearchResult(TopDocs queryResult)
        {
            if (queryResult == null || queryResult.totalHits == 0)
            {
                SetOutput("Sorry，没有搜索到你要的结果。");
                return;
            }

            int counter = 1;
            foreach (ScoreDoc sd in queryResult.scoreDocs)
            {
                try
                {
                    Document doc = new Program().searcher.Doc(sd.doc);
                    string id = doc.Get("ID");//获取id
                    string fileName = doc.Get("Name");//获取文件名
                    string contents = doc.Get("Info");//获取文件内容
                    string result = string.Format("这是第{0}个搜索结果,Id为{1},Name:{2},Info:{3}", counter, id, fileName, doc.Get("Info"));
                    SetOutput(result);
                }
                catch (Exception ex)
                {
                    SetOutput(ex.Message);
                }
                counter++;
            }
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.editLucene();
            //  p.createLucene();


            // p.addLucene();
            //  p.deleteLucene();
            p.testLucene();


            Console.ReadKey();
        }

        void testLucene()
        {
            ShowFileSearchResult(new SearchResult().GetResult("神*", "Name", 100));
        }

        /// <summary>
        /// 先删除，再插入
        /// </summary>
        void editLucene()
        {
            Program p = new Program();
            IndexWriter writer = new IndexWriter(p.directory, p.analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
            Document doc = new Document();
            doc.Add(new Field("ID", "9084", Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("Name", "不是神人也", Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("Info", "要为每个字段赋值，否则为空123465", Field.Store.YES, Field.Index.ANALYZED));
            writer.DeleteDocuments(new Term("ID", "9084"));
            writer.AddDocument(doc);
            writer.Optimize();
            writer.Close();
        }

        void deleteLucene()
        {
            Program p = new Program();
            IndexWriter writer = new IndexWriter(p.directory, p.analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
            writer.DeleteDocuments(new Term("ID", "9084"));
            writer.Optimize();
            writer.Close();
        }


        void addLucene()
        {
            Program p = new Program();
            IndexWriter writer = new IndexWriter(p.directory, p.analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
            Document doc = new Document();
            doc.Add(new Field("ID", "51888888", Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("Name", "神人51888888", Field.Store.YES, Field.Index.ANALYZED));
            writer.AddDocument(doc);
            writer.Optimize();
            writer.Close();
        }



        void createLucene()
        {
            Program p = new Program();
            IndexWriter writer = new IndexWriter(p.directory, p.analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
            IList<Res_Item> list = new XXBDataContext().Res_Item.ToList();
            IndexDB(writer, list);
        }
        /// <summary>
        /// 从数据库写到文件
        /// </summary>
        /// <param name="modifier"></param>
        /// <param name="listModels"></param>
        static void IndexDB(IndexWriter modifier, IList<Res_Item> listModels)
        {
            Console.WriteLine(string.Format("正在建立数据库索引，共{0}人", listModels.Count));

            foreach (var item in listModels)
            {
                Document doc = new Document();//创建文档，给文档添加字段，并把文档添加到索引书写器里
                doc.Add(new Field("ID", item.ID.ToString(), Field.Store.YES, Field.Index.ANALYZED));//存储且索引
                if (!string.IsNullOrEmpty(item.Name))
                    doc.Add(new Field("Name", item.Name, Field.Store.YES, Field.Index.ANALYZED));//存储且索引
                if (!String.IsNullOrEmpty(item.Info))
                    doc.Add(new Field("Info", item.Info, Field.Store.YES, Field.Index.ANALYZED));//存储且索引
                modifier.AddDocument(doc);
            }
            modifier.Optimize();//优化索引
            modifier.Close();//关 闭索引读写器
        }



    }
}
